package org.example.mrrope.service;

import lombok.extern.slf4j.Slf4j;
import org.example.mrrope.utils.CusutUtil;
import org.example.mrrope.utils.DingUtil;
import org.example.mrrope.utils.FormUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * CYQ 切绳车间派工单
 */
@Service
@Slf4j
public class CuttingRopeWorkOrder {
    @Autowired
    DingUtil dingUtil;

    public Integer saveCuttingRopeWorkOrder(JSONObject jsonObject, String id, String userId) throws Exception {
        String s = null;
        if (jsonObject.has("tableField_m0en6p40")) {
            JSONObject newJoB = new JSONObject();
            List<String> list2 = new ArrayList<>();
            JSONArray szTable = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_m0en6p40");
            newJoB.put("dateField_m341fjeb", jsonObject.has("dateField_m2wwkxe3") ? jsonObject.get("dateField_m2wwkxe3") : System.currentTimeMillis());//完成截止时间
            //切绳子表
            for (int i = 0; i < szTable.length(); i++) {
                JSONObject jsObjectOne = szTable.getJSONObject(i);
                JSONObject newJo = new JSONObject(newJoB.toString());
                //判断绳子子表是否有信息
                String name = jsObjectOne.get("textField_m0en6p42").toString();
                String CoodId = jsObjectOne.get("textField_m0en6p3l").toString();
                if (!name.isEmpty() && !CoodId.isEmpty()) {
                    newJo.put("numberField_lzauhblt", jsObjectOne.has("numberField_m0en6p3s") ? jsObjectOne.get("numberField_m0en6p3s") : 0);//切绳重量
                    newJo.put("textField_m2iv6alz", jsObjectOne.has("textField_m2ofu1y0") ? jsObjectOne.get("textField_m2ofu1y0") : 0);//切绳误差范围
                    newJo.put("textField_m2iv6am2", jsObjectOne.has("textField_m0en6p3r") ? jsObjectOne.get("textField_m0en6p3r") : "");//切绳规格
                    newJo.put("numberField_lzauhbls", jsObjectOne.has("numberField_m0en6p3t") ? jsObjectOne.get("numberField_m0en6p3t") : 0);//切绳长度
                    double qszl = 0.0;
                    if(jsObjectOne.has("numberField_m0en6p3s")){
                        qszl = Double.parseDouble(jsObjectOne.get("numberField_m0en6p3s").toString());//切绳重量
                    }
                    double sczl = 0.0;
                    double sJsczl = 0.0;
                    if (jsObjectOne.has("numberField_m0en6p3x")) {
                        sczl = Double.parseDouble(jsObjectOne.get("numberField_m0en6p3x").toString());//生产总量
                    }
                    if (jsObjectOne.has("numberField_m607dwou")){
                        sJsczl = Double.parseDouble(jsObjectOne.get("numberField_m607dwou").toString());//实际生产总量
                    }
//                    double qsgs = Math.ceil(sczl * 1000 / qszl);
                    double bzylgs = 0.0;//标准用量根数
                    if (jsObjectOne.has("numberField_m27fgapz")) {
                        bzylgs = Double.parseDouble(jsObjectOne.get("numberField_m27fgapz").toString());//标准用量（根数）
                    }
                    newJo.put("numberField_m3gzh0pg", bzylgs);//标准用量（根数）
//                    newJo.put("numberField_lzauhblw", qsgs);//切绳根数
                    newJo.put("numberField_lugarhfl", sczl);//总应发数量

                    // ---------------------------半成品信息---------------------------
                    String bOMB = jsObjectOne.get("textField_m0en6p3k").toString();
                    String bOMName = null;
                    String bOMImg = null;
                    String bOOMType = null;
                    Double bOOMBjYL = null;
                    if (jsonObject.has("tableField_lwed3a1x")) {
                        JSONArray jsonBTow = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_lwed3a1x");
                        for (int j = 0; j < jsonBTow.length(); j++) {
                            JSONObject jsonBTow2 = jsonBTow.getJSONObject(j);
                            if (jsonBTow2.get("textField_lujgt592").equals(bOMB)) {
                                bOMName = jsonBTow2.getString("textField_lwbmqipz");
                                bOMImg = jsonBTow2.has("textField_lxk8d6fo") ? jsonBTow2.getString("textField_lxk8d6fo") : null;
                                bOOMType = jsonBTow2.has("textareaField_m2ohpz46") ? jsonBTow2.getString("textareaField_m2ohpz46") : null;
                                bOOMBjYL = jsonBTow2.has("numberField_m5z1tmyo") ? jsonBTow2.getDouble("numberField_m5z1tmyo") : 1;
                                break;
                            }
                        }
                    }
                    newJo.put("numberField_lzauhblw", bOOMBjYL*bzylgs);//切绳根数 半成品总应发量*标准用量根数
                    newJo.put("numberField_m607vmnb", sJsczl);//实际总应发数量
                    newJo.put("radioField_m42cd3fr", "正常");//派工单状态
                    JSONObject searchScheduleJson = new JSONObject();
                    searchScheduleJson.put("textField_lyz55iot", jsonObject.get("textField_lwt4u8ls"));//so号
                    searchScheduleJson.put("textField_lugarhfd", jsObjectOne.get("textField_m0en6p3k"));//半成品号
                    searchScheduleJson.put("textField_lz9w4941", jsObjectOne.get("textField_m0en6p42"));//绳子C号
                    searchScheduleJson.put("textField_m0eww2wu", jsObjectOne.get("textField_m0en6p3l"));//绳段H号
                    String yiDaSearchReturnData_Schedule = dingUtil.yiDaSearchReturnData("FORM-B97E6005D3AD4586ABAB879F7DF68C91UQNE", searchScheduleJson);//获取缝纫派工单数据
                    JSONArray yiDaSearchReturnData_ScheduleJsonArray = new JSONArray(yiDaSearchReturnData_Schedule);
                    if (!yiDaSearchReturnData_ScheduleJsonArray.isEmpty()) {
                        String oid = yiDaSearchReturnData_ScheduleJsonArray.getJSONObject(0).getString("formInstanceId");
                        JSONObject zsObject = new JSONObject(dingUtil.getYidaById(oid));//原有派工单
                        Double todoAmount = bOOMBjYL*bzylgs;//应有的待完成量
                        Double finishedAmount = zsObject.has("numberField_lz9xbp39") ? zsObject.getDouble("numberField_lz9xbp39") : 0.0;//已完成量
                        newJo.put("numberField_lz9xbp3a", todoAmount - finishedAmount);//待上交总量
                        log.info("更新 切绳车间派工单开始");
                        log.info("更新oid:{}", oid);
                        log.info("更新数据:{}", newJo);
                        dingUtil.UpdateYiDa(oid, newJo);//更新生产计划
                        log.info("更新 切绳车间派工单完成");
                    } else {
                        //下发派工单
                        newJo.put("textField_lyz55iot", jsonObject.get("textField_lwt4u8ls"));//SO号
                        newJo.put("textField_lx1mddjk", jsonObject.get("textField_lujgt578"));//客户名称
                        newJo.put("textField_lugarhfe", jsonObject.get("textField_lujgt577"));//客户货号
                        newJo.put("radioField_mann5ewv", jsonObject.has("radioField_makqj7pg")?jsonObject.get("radioField_makqj7pg"):"苍南");//工厂
                        newJo.put("textField_m2u54ytt", jsonObject.has("textField_m2e5ira7") ? jsonObject.get("textField_m2e5ira7") : "");//PO
                        //-----------------绳子信息-----------------
                        newJo.put("textField_lugarhfd", jsObjectOne.get("textField_m0en6p3k"));//半成品B号
                        newJo.put("textField_lz9w4941", jsObjectOne.get("textField_m0en6p42"));//绳子C号
                        newJo.put("textField_m0eww2wu", jsObjectOne.get("textField_m0en6p3l"));//绳段H号
                        newJo.put("textField_m3f920ie", jsObjectOne.get("textField_m0en6p3m"));//绳段名称
                        newJo.put("textField_lza0wrkk", jsObjectOne.has("textField_m0eus6gn") ? jsObjectOne.get("textField_m0eus6gn") : null);//绳子名称
                        newJo.put("textField_lugarhg6", jsObjectOne.get("textField_m3f9ddxa"));//绳子规格
                        newJo.put("imageField_lugarhfm", jsObjectOne.has("imageField_m0en6p3y") ? jsObjectOne.get("imageField_m0en6p3y") : null);//绳段图片
                        newJo.put("numberField_lz9xbp3a", bOOMBjYL*bzylgs);//待上交总量
                        newJo.put("numberField_lz9xbp39", 0);//已上交总量
                        newJo.put("numberField_m3hiyoxi", 0);//已入库总量
                        newJo.put("textField_lz9yqpfp", CusutUtil.getRandomString(11));//uuid


                        JSONArray bcp_upArray = new JSONArray();
                        JSONObject listOnZhiJie = new JSONObject();
                        listOnZhiJie.put("textField_m3fb09e9", jsObjectOne.get("textField_m0en6p42"));//绳子c号
                        listOnZhiJie.put("textField_m3fb09ea", jsObjectOne.has("textField_m0eus6gn") ? jsObjectOne.get("textField_m0eus6gn") : null);//绳子名字
                        listOnZhiJie.put("textField_m3fb09eb", jsObjectOne.get("textField_m3f9ddxa"));//规格
                        bcp_upArray.put(listOnZhiJie);
                        newJo.put("textField_lugarhgb", bOMImg);//切绳注意点
                        newJo.put("tableField_m3fb09e7", bcp_upArray);//绳子子表
                        newJo.put("textField_lxifktd1", bOMName);//成品名称
                        newJo.put("textField_m2xgr8fo", bOOMType);//半成品规格与重量
                        //---------------------------关联BOM---------------------------
                        String title = jsonObject.getString("textField_lwt4u8ls");
                        String fromUuid = "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW";
                        // 通过调用FormUtils的getAssociationFormField方法，根据fromUuid、title和id获取关联表单字段的JSON数组
                        JSONArray jsonArrayOne = FormUtils.getAssociationFormField(fromUuid, title, id);
                        newJo.put("associationFormField_lwt4miug", jsonArrayOne);
                        log.info("关联半成品BOM" + jsonArrayOne);
                        s = dingUtil.startInstance(newJo, userId, "FORM-B97E6005D3AD4586ABAB879F7DF68C91UQNE");
                        log.info("YIDA-startInstance 切绳派工单生成数据" + s);
                    }
                }
                list2.add(jsObjectOne.has("textField_m0en6p3l") ? jsObjectOne.getString("textField_m0en6p3l") : "");
             }
            //查找现有的派工单，进行循环，多余的派工单删除
            //根据SO号搜索
            JSONObject paiGonJson = new JSONObject();
            paiGonJson.put("textField_lyz55iot", jsonObject.has("textField_lwt4u8ls") ? jsonObject.get("textField_lwt4u8ls") : "");//so号
            String yiDaPaiGonString = dingUtil.yiDaSearchReturnData("FORM-B97E6005D3AD4586ABAB879F7DF68C91UQNE", paiGonJson);//获取派工单数据
            JSONArray yiDaPaiGonJsonArray = new JSONArray(yiDaPaiGonString);
            HashMap<String, String> newMap = new HashMap<>();
            List<String> list1 = new ArrayList<>();
            //把C号存在容器里面
            for (int i = 0; i < yiDaPaiGonJsonArray.length(); i++){
                String oid = yiDaPaiGonJsonArray.getJSONObject(i).getString("formInstanceId");
                JSONObject pgdObject = new JSONObject(dingUtil.getYidaById(oid));//原有派工单
                if (pgdObject.has("textField_m0eww2wu")){
                    list1.add(pgdObject.getString("textField_m0eww2wu"));
                    newMap.put(pgdObject.getString("textField_m0eww2wu"),oid);
                }
            }
            // 找出派工单中有但生产计划中没有的元素
            // 派工单 减 生产计划 多出来的就是没用的派工单
            list1.removeAll(list2);
            if (list1.size() > 0){
                for (String numberC : list1) {
                    //删除多余的派工单
                    if (newMap.containsKey(numberC)){
                        JSONObject object = new JSONObject();
                        object.put("radioField_m42cd3fr", "暂停");
                        dingUtil.UpdateYiDa(newMap.get(numberC), object);
//                        dingUtil.delete(newMap.get(numberC));
                    }
                }
            }
        }
        return s == null ? 1 : 0;
    }
}
